package DroidEye;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;

@ComponentScan(basePackages = "DroidEye")
@ServletComponentScan(basePackages = "DroidEye")
@SpringBootApplication
@MapperScan("DroidEye.Mapper")
@EnableTransactionManagement
public class HelloApplication extends SpringBootServletInitializer{
    private static final Logger logger = LoggerFactory.getLogger(HelloApplication.class);
    private static ConfigurableApplicationContext applicationContext;

    public static void main(String[] args) throws UnknownHostException {
        applicationContext = SpringApplication.run(HelloApplication.class, args);
        Environment env = applicationContext.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        if (StringUtils.isEmpty(path)) {
            path = "";
        }
        logger.info("\n----------------------------------------------------------\n\t" +
                "Application  is running! Access URLs:\n\t" +
                "Local访问网址: \t\thttp://localhost:" + port + path + "index.jsp\n\t" +
                "External访问网址: \thttp://" + ip + ":" + port + path + "index.jsp\n" +
                "----------------------------------------------------------");
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(HelloApplication.class);
    }

    /**
     * 获取applicationContext中的bean.
     *
     * @param name         beanId
     * @param requiredType bean类型
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return getApplicationContext().getBean(name, requiredType);
    }
}
